package com.qrcode.scan.camera;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.content.ContextCompat;

import com.qrcode.scan.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageUtil {

    public final static int IMAGE_WIDTH_MAX = 1080;
    public final static int IMAGE_HEIGHT_MAX = 1920;

    public static Bitmap getRotateBitmap(Bitmap b, float rotateDegree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotateDegree);
        return Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, false);
    }


    public static Bitmap getRotateBitmap_front(Bitmap b, float rotateDegree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotateDegree);
        //postScale 解决前置 左右相反的问题
        matrix.postScale(-1, 1);
        return Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, false);
    }

    public static void drawTextTo(Context context, String imagePath, String textWater, String outFile) {
        Log.e("drawTextTo 准备添加水印",  "drawTextTo start"+imagePath);
        try {
            Bitmap bitmap = compressImageFromFile(imagePath, IMAGE_WIDTH_MAX, IMAGE_HEIGHT_MAX);

            // 小米手机不允许直接对资源文件进行修改
      /*  android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
        // 需要一个默认的config
        if (bitmapConfig == null) {
            bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
        }*/

            Bitmap.Config bitmapConfig = bitmap.getConfig() != null ? bitmap.getConfig() : Bitmap.Config.ARGB_8888;
            // 需要拷贝一份可变（mutable）bitmap
            bitmap = bitmap.copy(bitmapConfig, true);

            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            if(width<60){
                Log.e("drawTextTo 准备添加水印","图片太窄无法添加水印");
                return;
            }

            Canvas canvas = new Canvas(bitmap);
            //透明背景画笔
            Paint paintBg = new Paint(Paint.ANTI_ALIAS_FLAG);
            paintBg.setColor(ContextCompat.getColor(context, R.color.color_6));
            //文字画笔
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG
                    | Paint.DEV_KERN_TEXT_FLAG);
            paint.setTextSize(22);
            paint.setTypeface(Typeface.DEFAULT);
            paint.setColor(Color.RED);
            paint.setDither(true); // 获取跟清晰的图像采样
            paint.setFilterBitmap(true);// 过滤一些

            String strDateTime = TimeUtils.milMillis2String(System.currentTimeMillis(),//时分秒 时间戳
                    "yyyy-MM-dd HH:mm:ss");
            //dateStr = dateStr.substring(0, 16);

            int marginLeft = StatusBarUtil.dp2px (context,80);
            setPaint(paint, strDateTime + textWater, width);//设置画笔字大小
            float dateWidth = paint.measureText(strDateTime);//获取日期宽度
            Paint.FontMetrics fm = paint.getFontMetrics();
            float textHeight = fm.descent - fm.ascent;
            //画文字透明背景
            canvas.drawRect(0, height - textHeight * 2, width, height, paintBg);

            String strContent = textWater + "   " + strDateTime;
            canvas.drawText(strContent, marginLeft, height - textHeight / 2, paint);
            Log.e("drawTextTo 准备添加水印","textWater:"+textWater);
          /*  //画右边的日期
            canvas.drawText(strDateTime, width - dateWidth - marginLeft, height - textHeight / 2, paint);
            // 左边显示名称
            canvas.drawText(strUserName, marginLeft, height - textHeight / 2, paint);
            canvas.drawText(strLogo, marginLeft, height - textHeight * 2, paint);*/


            File file = new File(outFile);// 将要保存图片的路径
            try {
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("drawTextToBitmap Error", "error" + e.getMessage());
            }

            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("drawTextToBitmap Error", "error" + e.getMessage());
        }
        Log.e("添加水印结束  drawTextTo end", outFile);

    }

    public static void setPaint(Paint paint, String text, int width) {
        float dateWidth = 0;
        do {
            dateWidth = paint.measureText(text) + 20 * 2 + 20;
            if (dateWidth <= width) {
                break;
            }
            paint.setTextSize(paint.getTextSize() - 1);
        } while (true);
    }



    /**
     * 压缩图片
     * @param srcPath
     * @param maxWidth
     * @param maxHeight
     * @return
     */
    public static Bitmap compressImageFromFile(String srcPath, int maxWidth, int maxHeight) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;// 只读边,不读内容
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        int be = 1;
        float scale = 0.0f;
        if (w > maxWidth || w > maxHeight || h > maxWidth || h > maxHeight) {
            if (w > h) {
                if (maxHeight > maxWidth) {
                    int temp = maxHeight;
                    maxHeight = maxWidth;
                    maxWidth = temp;
                }
            } else {
                if (maxWidth > maxHeight) {
                    int temp = maxHeight;
                    maxHeight = maxWidth;
                    maxWidth = temp;
                }
            }

            if (w * maxHeight > h * maxWidth) {
                be = w / maxWidth;
                if (be <= 0) {
                    be = 1;
                }
                scale = ((float) (maxWidth * be)) / w;
            } else {
                be = h / maxHeight;
                if (be <= 0) {
                    be = 1;
                }
                scale = ((float) (maxHeight * be)) / h;
            }
        }
        newOpts.inSampleSize = be;// 设置采样率

        newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888;// 该模式是默认的,可不设
        newOpts.inPurgeable = true;// 同时设置才会有效
        newOpts.inInputShareable = true;// 。当系统内存不够时候图片自动被回收

        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        if (scale > 0) {
            Matrix matrix = new Matrix();
            matrix.setScale(scale, scale);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), matrix, true);
        }

        return bitmap;
    }

}
